package upicgame.gamelibrary.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import upicgame.cart.dao.CartDao;
import upicgame.entity.Game;
import upicgame.entity.Library;
import upicgame.entity.User;
import upicgame.gamelibrary.dao.LibraryDao;
import upicgame.utils.Page;
@Service
@Transactional
public class LibraryService {
	@Autowired
	private LibraryDao ld;
	@Autowired
	private CartDao cd;
	public List<Library> getLibrary(){
		List<Library> list = ld.findAllLibrary();
		return list;
	}
	
	public List<Library> getLibraryByUid(Integer uid){
		List<Library> list = new ArrayList<Library>();
		List<Object[]> obj = ld.findLibraryByUserId(uid);
		for(Object[] item:obj) {
			User user = new User();
			user.setId((int)item[1]);
			user.setName(item[3].toString());
			Game game = new Game();
			game.setId((int)item[4]);
			game.setName(item[5].toString());
			list.add(new Library((int)item[0],user,game));
		}
		return list;
	}
	
	
	public Page<Library> findAllLibraryByPage(Integer currentPage, Integer maxSize) {
		List<Library> list = ld.findAllLibraryByPage(currentPage, maxSize);
		Integer totalCount = ld.countLibGame().intValue();
		Page<Library> page = new Page<>(currentPage, maxSize, list);
		page.setTotalCount(totalCount);
		return page;
	}
	
	
	public Page<Library> getLibraryByPage(Integer uid, Integer currentPage, Integer maxSize) {
		List<Library> list = ld.pageFindLibByUser(uid, currentPage, maxSize);
		Integer totalCount = ld.countLibGame(uid).intValue();
		Page<Library> page = new Page<>(currentPage, maxSize, list);
		page.setTotalCount(totalCount);
		return page;
	}
	

	
	public boolean addGameInLibrary(Integer uid,Integer gid) {
		try {
			Library temp = ld.findlibByUserAndGame(uid, gid);
			if(temp==null) {
				User user = new User(uid);
				Game game = new Game(gid);
				Library lib = new Library(user,game);
				ld.addGameInLibrary(lib);
				return true;
			}else {
				return false;
			}
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean delGameInLibrary(Integer uid,Integer gid) {
		Integer result = ld.delGameInLibrary(uid, gid);
		return result>0?true:false;
	}
	
	public List<User> findAllUser(){
		List<User> user = ld.findAllUser();

		return user;
	}
}
